package com.three.common.message.base;

import com.google.protobuf.InvalidProtocolBufferException;
import com.three.api.connection.Connection;
import com.three.api.protocol.Packet;
import com.three.protocol.BaseModule;
import com.three.protocol.CommandEnum;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.three.protocol.CommandEnum.Command.OK;

/**
 * Created by mathua on 2017/5/28.
 */
public final class OkMessage extends BaseMessage {
    private short cmd;
    private short code;
    private String msg;
    private List<String> data = new ArrayList<>();

    public OkMessage(short cmd, Packet message, Connection connection) {
        super(message, connection);
        this.cmd = cmd;
    }

    public OkMessage(Packet message, Connection connection) {
        super(message, connection);
    }

    @Override
    public void decode(byte[] body) throws InvalidProtocolBufferException {
        BaseModule.Ok_9 bodyData = BaseModule.Ok_9.parseFrom(body);
        cmd = (short) bodyData.getCmd().getNumber();
        if(bodyData.hasCode())
            code = (short) bodyData.getCode();
        if(bodyData.hasMsg())
            msg = bodyData.getMsg();
        data = bodyData.getDataList();
    }

    @Override
    public byte[] encode() {
        BaseModule.Ok_9.Builder builder = BaseModule.Ok_9.newBuilder();
        builder.setCmd(CommandEnum.Command.valueOf(cmd));
        if(code != 0)
            builder.setCode(code);
        if(msg != null)
            builder.setMsg(msg);
        if(!data.isEmpty())
            builder.addAllData(data);
        return builder.build().toByteArray();
    }


    @Override
    public Map<String, Object> encodeJsonBody() {
        Map<String, Object> body = new HashMap<>(3);
        if (cmd > 0) body.put("cmd", cmd);
        if (code > 0) body.put("code", code);
        if (data != null) body.put("data", data);
        return body;
    }

    public static OkMessage from(BaseMessage src) {
        return new OkMessage(src.packet.cmd, src.packet.response(OK), src.connection);
    }

    public OkMessage setCode(short code) {
        this.code = code;
        return this;
    }

    public OkMessage setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public OkMessage addData(String... data) {
        for(String tmp : data) {
            this.data.add(tmp);
        }
        return this;
    }

    @Override
    public String toString() {
        return "OkMessage{" +
                "cmd=" + cmd +
                ", code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }

    public short getCmd() {
        return cmd;
    }

    public short getCode() {
        return code;
    }

    public List<String> getData() {
        return data;
    }

    public String getMsg() {
        return msg;
    }
}

